﻿using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Read.API.Application.Command.HospitalNavigationCommand;
using D.Medicalcare.Read.API.Application.Command.MessageCommand;
using D.Medicalcare.Read.API.Application.Handler.MessageHandler;
using MediatR;

namespace D.Medicalcare.Read.API.Application.Handler.HospitalNavigationHandler
{
    /// <summary>
    /// 查询医院导航信息处理类
    /// </summary>
    public class GetHospitalNavigationHandler : IRequestHandler<GetHospitalNavigationCommand, APIPaging<HospitalNavigation>>
    {
        private readonly IBaseRepository<HospitalNavigation> prep;
        private readonly ILogger<GetHospitalNavigationHandler> logger;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="prep">仓储</param>
        /// <param name="logger">日志</param>
        public GetHospitalNavigationHandler(IBaseRepository<HospitalNavigation> prep, ILogger<GetHospitalNavigationHandler> logger)
        {
            this.prep = prep;
            this.logger = logger;
        }
        /// <summary>
        /// 处理
        /// </summary>
        public  async Task<APIPaging<HospitalNavigation>> Handle(GetHospitalNavigationCommand request, CancellationToken cancellationToken)
        {
            APIPaging<HospitalNavigation> result = new APIPaging<HospitalNavigation>();
            try
            {
                var list = prep.GetAll().Where(x => x.IsDeleted == false);
                if (!string.IsNullOrEmpty(request.CampusName))
                {
                    list = list.Where(x => x.CampusName!.Contains(request.CampusName)) ;
                }
                result.Code = APIEnum.Mvc;
                result.Msg = "查询成功";
                logger.LogInformation(result.Msg);
                result.TotalCount = list.Count();
                result.PageCount = (int)Math.Ceiling(result.TotalCount * 1.0 / request.PageSize);
                result.Data = list.OrderByDescending(x => x.HospitalNavigationId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                return await  Task.FromResult(result);
            } 
            catch (Exception ex)
            {
                logger.LogError("查询异常" + ex.Message);

                throw;
            }

        }
    }
}

